# coding: utf-8

from __future__ import print_function

import logging
import logging.config
import os
from logging.handlers import RotatingFileHandler

import config


class LoggerHandler(object):
    _instance = None
    def __new__(cls, *args, **kw):
        if not cls._instance:
            cls._instance = super(LoggerHandler, cls).__new__(cls, *args, **kw)
        return cls._instance

    def __init__(self, console_level=logging.INFO, file_level=logging.NOTSET):
        log_file_name = os.path.join(config.LOG_DIRECTORY, '{0}{1}'.format(config.LOG_FILE, config.TIMESTAMP))
        # log_file_name = os.path.join(config.LOG_DIRECTORY, config.LOG_FILE)
        # if os.path.exists(log_file_name):
        #     copy_file_name = u'{0}{1}'.format(config.LOG_FILE, config.TIMESTAMP)
        #     os.rename(log_file_name, os.path.join(config.LOG_DIRECTORY, copy_file_name))
        console_message_format = '%(message)s'
        file_message_format = '%(asctime)s\t%(levelname)s: %(message)s'
        file_handler = RotatingFileHandler(log_file_name, maxBytes=1024 * 1024, backupCount=5)
        file_handler.setFormatter(logging.Formatter(file_message_format))
        file_handler.setLevel(file_level)
        stream_handler = logging.StreamHandler()
        stream_handler.setLevel(console_level)
        stream_handler.setFormatter(logging.Formatter(console_message_format))
        self.logger = logging.getLogger(config.LOG_NAME)
        self.logger.setLevel(logging.INFO)
        self.logger.addHandler(file_handler)
        self.logger.addHandler(stream_handler)
        error_filter = logging.Filter()
        def logger_filter(record):
            return console_level == record.levelno
        error_filter.filter = logger_filter
        # error_filter.filter = lambda r : r.msg.find('HTTP connection') == -1
        self.logger.addFilter(error_filter)
        self.prev_message = None

    def getMessage(self, message=None, size=config.LOG_SPLIT_SIZE):
        if message is None:
            message = config.LOG_SPLIT_LINE * (self.prev_message is None and size or len(self.prev_message))
        else:
            self.prev_message = message
        return message

    def info(self, message=None, split=False, size=config.LOG_SPLIT_SIZE):
        # self.logger.info(u'\033[1;32m {0} \033[0m '.format(message))
        self.logger.info(self.getMessage(message=message, size=size))
        if split:
            self.logger.info(self.getMessage())

    def debug(self, message=None, split=False, size=config.LOG_SPLIT_SIZE):
        # self.logger.debug(u'\033[1;34m {0} \033[0m '.format(message))
        self.logger.debug(self.getMessage(message=message, size=size))
        if split:
            self.logger.debug(self.getMessage())

    def warn(self, message=None, split=False, size=config.LOG_SPLIT_SIZE):
        # self.logger.warning(u'\033[1;33m{0}\033[0m '.format(message))
        self.logger.warning(self.getMessage(message=message, size=size))
        if split:
            self.logger.warning(self.getMessage())

    def error(self, message=None, split=False, size=config.LOG_SPLIT_SIZE):
        # self.logger.error(u'\033[1;31m {0} \033[0m '.format(message))
        self.logger.error(self.getMessage(message=message, size=size))
        if split:
            self.logger.error(self.getMessage())

    def log(self, message=None, split=False, size=config.LOG_SPLIT_SIZE):
        # print(u'\033[1;32m')
        # print(object)
        # print(u'\033[0m')
        print(self.getMessage(message=message, size=size))
        if split:
            print(self.getMessage())

logger = LoggerHandler()